package com.ls.lserp.modules.trade.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.order.entity.SpecimenProduction;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;
import com.ls.lserp.modules.trade.dao.BookingOrdersDao;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.trade.entity.BookingOrders;
import com.ls.lserp.modules.trade.entity.ConsignmentNote;
import com.ls.lserp.modules.trade.entity.Enchase;
import com.ls.lserp.modules.trade.entity.ShippingFormExcelEntity;



@Service
@Transactional(readOnly = false)
public class BookingOrdersService extends CrudService<BookingOrdersDao, BookingOrders>{
	
	 private static final String FORM_ID = null;
	@Autowired
	    private BookingOrdersDao bookingOrdersDao;
	// 审核表
	@Autowired
		private AuditInfoDao  auditInfoDao;
	 
	public Page<BookingOrders> findList(Page<BookingOrders> page, BookingOrders bookingOrders) {
				// tab页分，检索条件设定(0:全部,1:已删除)
				int tabFlg = bookingOrders.getTabPageStatus();
				bookingOrders.setBookingOrdersDelFlg(BookingOrders.DEL_FLAG_NORMAL);
				if (tabFlg == 1) {
					bookingOrders.setBookingordersStatus("0");
				}else if(tabFlg == 2){
					bookingOrders.setBookingordersStatus("1");
				}else if(tabFlg == 3){
					bookingOrders.setBookingOrdersDelFlg(BookingOrders.DEL_FLAG_DELETE);
				}
		
				 // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
		        //designOption.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
		        // 设置分页参数
				bookingOrders.setPage(page);
				bookingOrders.setDelect(ResourcesUtil.getConfig("booking_orders"));
				List<BookingOrders> resultList = bookingOrdersDao.findList(bookingOrders);
		        // 执行分页查询
		        page.setList(bookingOrdersDao.findList(bookingOrders));
		        return page;
		}
	
	
	
	/**
	 * @Title: 选择款式装箱单一览
	 * @Description: 一览查询
	 * @param page
	 * @param enchase
	 * @return Page<Enchase>
	 */
	public Page<Enchase> findpackingList(Page<Enchase> page, Enchase enchase) {
		// 设置分页参数
		enchase.setPage(page);
		enchase.setEnchaseDelFlg(Enchase.DEL_FLAG_NORMAL);
		// 执行分页查询
		page.setList(bookingOrdersDao.findpackingList(enchase));
		return page;
	}
	
	/**
	 * @Title: 新建订舱委托单
	 * @Description: 查询
	 * @param indentId
	 * @return BookingOrders
	 */
	public BookingOrders getBookingOrderByIndentId(BookingOrders bookingOrders) {
		BookingOrders bo = new BookingOrders();
		List<BookingOrders> resultBookingOrders = bookingOrdersDao.getBookingOrderByIndentId(bookingOrders);
		   
		if(!CollectionsUtils.isEmpty(resultBookingOrders)){
			 bo.setBookingOrderList(resultBookingOrders);
	    }		
		return bo;
	}

	

	
	/**
	 * check BigDecimal
	 * @param cost
	 * @return 取不到返回0
	 */
	private BigDecimal checkBigDecimalNull(BigDecimal cost) {
		if(cost==null){
			return new BigDecimal("0");
		}
		return cost;
	}

	/**
	  * @Title: saveDict
	  * @Description: 保存基准数据
	  * @param @param dict
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveBookingOrders(BookingOrders bookingOrders) {
		
		// 判断新建编辑
		//若为null 执行插入语句（新建）
		if (bookingOrders.getId()==null){			
			bookingOrders.preInsert();
			bookingOrders.setVersion(1L);
			
			// 取得委托单编号
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");  
	        String dateNowStr = sdf.format(new Date());  
	        bookingOrders.setHsCode("B." + bookingOrders.getOgnizationShortName() + "." + dateNowStr);
	        //设置订舱区分为大货
	        bookingOrders.setFormFlag("0");
			if(StringUtils.isEmpty(bookingOrders.getBookingordersStatus())){
				// 设置委托单状态
				bookingOrders.setBookingordersStatus(ResourcesUtil.getConfig("bookingorders_status_begin"));
			}
			bookingOrdersDao.insertBookingorders(bookingOrders);
			
		}
		//编辑
		else{
			// 更新数据
			bookingOrders.preUpdate();
			bookingOrdersDao.update(bookingOrders);
			
		}
			// 判断list是否为空
			if(!CollectionsUtils.isEmpty(bookingOrders.getBookingOrderList())){
				// 遍历赋值
		        for(BookingOrders  hb : bookingOrders.getBookingOrderList()){
	        		//创建人信息
	        	    hb.preInsert();
	        	    hb.setVersion(1L);
	        	    hb.setId(bookingOrders.getId());
	        	    bookingOrdersDao.insertShippingDetails(hb);
		        }
			}
	}

	/**
     * 导出订舱明细
     *
     * @throws IOException
     */
    public ExcelTemplate exportExcel(BookingOrders bookingOrders , String tempFilePath) throws IOException {
    	// 返回值
    	ExcelTemplate handle = new ExcelTemplate();
    	//输出基本信息
    	List<ShippingFormExcelEntity> sList = bookingOrdersDao.findDataForExport(bookingOrders);
    	printBookingOrdersInfoTemp(tempFilePath,sList,handle);
    	//大货合同
    	//printInvoiceStyleInfoTemp(tempFilePath,bigcargoOrderList,null,null,handle);
        
        return handle;

    }
	
    /**
     * 
     * @param tempFilePath
     * @param ognization
     * @param handle
     * @throws IOException
     */
    private void printBookingOrdersInfoTemp(String tempFilePath, List<ShippingFormExcelEntity> sList, ExcelTemplate handle) throws IOException {
    	// 变量声明
    	List<String> dataCellDeclare = new ArrayList<String>();
    	// 变量值集合
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        // 变量值
        Map<String, Object> map = new HashMap<String, Object>();
        ShippingFormExcelEntity tempBean = new ShippingFormExcelEntity();
        // 合同号
        dataCellDeclare.add("contractNo");
        // 走货去向
        dataCellDeclare.add("pod");
        // 加工方式
        dataCellDeclare.add("maketype");
        // 款号
        dataCellDeclare.add("styleCustomNo");
        // 品番
        dataCellDeclare.add("size");
        // 数量
        dataCellDeclare.add("quantity");
        // 箱数
        dataCellDeclare.add("cartonQuantity");
        // 体积
        dataCellDeclare.add("cartonVolume");
        // G
        dataCellDeclare.add("Gkg");
        // N
        dataCellDeclare.add("Nkg");
        // 名称
        dataCellDeclare.add("styleName");
        // 日期
        dataCellDeclare.add("date");
        // 成分
        dataCellDeclare.add("composition");
        if (sList != null && sList.size() > 0) {
        	for (int i = 0; i < sList.size(); i++) {
        		if (sList.get(i) != null) {
        			map = new HashMap<String, Object>();
        			tempBean = sList.get(i);
        			// 合同号
        			map.put("contractNo", tempBean.getContractNo());
        	        // 走货去向
        			map.put("pod", tempBean.getPod());
        	        // 加工方式
        			map.put("maketype", tempBean.getMaketype());
        	        // 款号
        			map.put("styleCustomNo", tempBean.getStyleCustomNo());
        	        // 品番
        			map.put("size", DictUtils.getDictName(tempBean.getSize()));
        	        // 数量
        			map.put("quantity", tempBean.getQuantity());
        	        // 箱数
        			map.put("cartonQuantity", tempBean.getCartonQuantity());
        	        // 体积
        			map.put("cartonVolume", tempBean.getCartonVolume());
        	        // G
        			map.put("Gkg", tempBean.getGkg());
        	        // N
        			map.put("Nkg", tempBean.getNkg());
        	        // 名称
        			map.put("styleName", tempBean.getStyleName());
        	        // 日期
        			map.put("date", tempBean.getDate());
        	        // 成分
        			map.put("composition", tempBean.getComposition());
        			dataList.add(map);
        		}
        	}
		}else{
			map = new HashMap<String, Object>();
			// 合同号
			map.put("contractNo", "");
	        // 走货去向
			map.put("pod", "");
	        // 加工方式
			map.put("maketype", "");
	        // 款号
			map.put("styleCustomNo", "");
	        // 品番
			map.put("size", "");
	        // 数量
			map.put("quantity", "");
	        // 箱数
			map.put("cartonQuantity", "");
	        // 体积
			map.put("cartonVolume", "");
	        // G
			map.put("Gkg", "");
	        // N
			map.put("Nkg", "");
	        // 名称
			map.put("styleName", "");
	        // 日期
			map.put("date", "");
	        // 成分
			map.put("composition", "");
			dataList.add(map);
    	}
     // 向excel表输出
        handle.writeListDataCustom(tempFilePath, dataCellDeclare, dataList, 0, -1, "true" , 10);
    }
	
	/**
	* @Title: deleteBookingOrders
	* @Description: 删除订舱委托单(逻辑删除)
	* @param @param bookingOrders
	* @return void 
	* @throws
	*/
	@Transactional(readOnly = false)
	public void deleteBookingOrders(BookingOrders bookingOrders) {
		// 执行逻辑删除
		bookingOrdersDao.delete(bookingOrders);
	}
	
	/**
	* @Title: commitBookingOrders
	* @Description: 提交订舱委托单
	* @param bookingOrders
	* @return void 
	* @throws
	*/
	@Transactional(readOnly = false)
	public void commitBookingOrders(BookingOrders bookingOrders) {
		bookingOrders.preUpdate();
		bookingOrders.setBookingordersStatus("1");
		bookingOrdersDao.commit(bookingOrders);
		
	}
	
	
    /**
     * @Title: findAuditList
     * @Description: 查询所有履历
     * @param @param auditInfo
     * @param @return
     * @return List<AuditInfo> 
     * @throws
     */
   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
	   AuditInfo audit = new AuditInfo();
	   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
	   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
       // 执行查询
       return audit;
   }
   
   /**
    * @Title: getAuditResult
    * @Description: 审核结果
    * @param @param auditInfo
    * @param @return
    * @return 审核结果通过数
    * @throws
    */
  
  public long getAuditResult(AuditInfo auditInfo) {
	   
      return auditInfoDao.findAuditAcceptCount(auditInfo);
  }
  
  /**
	  * @Title: saveAudit
	  * @Description: 保存履历信息
	  * @param @param auditInfo
	  * @return void 
	  * @throws
	  */
	@Transactional(readOnly = false)
	public void saveAuditInfo(AuditInfo auditInfo) {
		
		 // 插入履历表
	     auditInfo.preInsert();
	     auditInfo.setAuditDate(new Date());
	     auditInfo.setAuditUserId(UserUtils.getUser().getId());
      // 新建版本号赋值1
	     auditInfo.setVersion(1L);
	     auditInfoDao.insert(auditInfo);
	     
	     // 
	     auditInfo.preUpdate();
	     bookingOrdersDao.updateBookingordersStatus(auditInfo);
	}

	/**
	 * 查询一条采购合同信息
	 * @param user
	 * @return
	 */
	public BookingOrders getBooking(BookingOrders bookingOrders) {
	
		return bookingOrdersDao.get(bookingOrders);
	}
	/**
	 * ID查询信息 
	 * @param user
	 * @return
	 */
	public List<BookingOrders> findBookingByID(BookingOrders bookingOrders) {
//		 BookingOrders bo = new BookingOrders();
//		 List<BookingOrders> resultFindBooking = bookingOrdersDao.findBookingByID(bookingOrders);
//		 if(!CollectionsUtils.isEmpty(resultFindBooking)){
//			   bo.setBookingOrderList(resultFindBooking);	     		
//	      }
		 return bookingOrdersDao.findBookingByID(bookingOrders);
	}



	
	
	
	

	
}
